package io.renren.modules.diycake.service.impl;

import io.renren.modules.diycake.entity.VedioEntity;
import io.renren.modules.diycake.service.VedioService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;

import java.io.*;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.diycake.dao.FileDao;
import io.renren.modules.diycake.entity.FileEntity;
import io.renren.modules.diycake.service.FileService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Service("fileService")
@Slf4j
public class FileServiceImpl extends ServiceImpl<FileDao, FileEntity> implements FileService {
  @Autowired
  private VedioService vedioService;

  @Autowired
  private HttpServletRequest request;

  @Autowired
  private HttpServletResponse response;

  @Override
  public PageUtils queryPage(Map<String, Object> params) {
    IPage<FileEntity> page = this.page(
            new Query<FileEntity>().getPage(params),
            new QueryWrapper<FileEntity>()
    );

    return new PageUtils(page);
  }

  @Override
  public String upload(MultipartFile file, Long cakeId) {
    try {
      if (file.isEmpty()) {
        return "文件为空";
      }
      // 获取文件名
      String fileName = file.getOriginalFilename();
      log.info("上传的文件名为：" + fileName);//写日志

      String filePath = "./CAKE/VEDIO/";
      String path = filePath + fileName;
      File dest = new File(new File(path).getAbsolutePath());// dist为文件，有多级目录的文件
      // 检测是否存在目录
      if (!dest.getParentFile().exists()) {//因此这里使用.getParentFile()，目的就是取文件前面目录的路径
        dest.getParentFile().mkdirs();// 新建文件夹
      }
      file.transferTo(dest);// 文件写入
      Long leastSignificantBits = UUID.randomUUID().getLeastSignificantBits();
      VedioEntity vedioEntity = new VedioEntity();
      vedioEntity.setVedioUrl("/diycake/file/" + leastSignificantBits);
      vedioEntity.setName(fileName);
      vedioEntity.setUuId(leastSignificantBits);
      vedioEntity.setCakeId(cakeId);
      vedioService.save(vedioEntity);
      return ""+leastSignificantBits;
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "上传失败";
  }

  @Override
  public String download(Long significantBits) throws UnsupportedEncodingException {
    VedioEntity fileEntity = vedioService.getOne(new QueryWrapper<VedioEntity>().eq("uu_id", significantBits));
    String fileName = fileEntity.getName();// 文件名
    if (fileName != null) {
      //设置文件路径
      java.io.File file = new java.io.File("./CAKE/VEDIO/"+fileEntity.getName());
      //File file = new File(realPath , fileName);
      if (file.exists()) {
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));// 设置文件名
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
          fis = new FileInputStream(file);
          bis = new BufferedInputStream(fis);
          OutputStream os = response.getOutputStream();
          int i = bis.read(buffer);
          while (i != -1) {
            os.write(buffer, 0, i);
            i = bis.read(buffer);
          }
          return "下载成功";
        } catch (Exception e) {
          e.printStackTrace();
        } finally { // 做关闭操作
          if (bis != null) {
            try {
              bis.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
          if (fis != null) {
            try {
              fis.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
    }
    return "下载失败";
  }

}